package com.java.test.exceptiontest;

/**
 * @author wangning
 * @create 2021-09-26 11:28
 */
public class ExceptionTest01 {
	public static void main(String[] args) {
		int[] arr = {1, 2, 3, 4, 5};
		int index = 6;
		int element = -1;
		try {
			element = getElement(arr,index);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("----------------");
			System.out.println(e);// java.lang.ArrayIndexOutOfBoundsException: 数组下标越界
			System.out.println(e.getMessage());// 数组下标越界
			System.out.println(e.toString());// java.lang.ArrayIndexOutOfBoundsException: 数组下标越界

		}

		System.out.println("element = " + element);
	}

	private static int getElement(int[] arr, int index) {
		// 判断索引是否越界
		if (index < 0 || index > arr.length - 1) {
			throw new ArrayIndexOutOfBoundsException("数组下标越界");
		}
		return arr[index];
	}
}
